package com.ishopping.web.manage.controller;

import com.ishopping.api.manage.entity.ShiroUser;
import com.ishopping.common.core.base.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录退出
 */
@Controller
public class LoginController extends BaseController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 访问首页
     * @return
     */
    @RequestMapping(value = "/")
    public String index() {
        return "redirect:/index";
    }

    /**
     * 访问首页
     * @param model
     * @return
     */
    @RequestMapping(value = "/index")
    public String index(Model model) {
        //从shiro的session中取activeUser
        Subject subject = SecurityUtils.getSubject();
        //取身份信息
        ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
        //通过model传到页面
        model.addAttribute("shiroUser", shiroUser);
        return "index";
    }

    /**
     * 登陆提交地址，和applicationContext-shiro.xml中配置的loginurl一致
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) throws Exception {
        //如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
        String defaultErrorKey = FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME;
        String exceptionClassName = (String) request.getAttribute(defaultErrorKey);
        model.addAttribute("error", exceptionClassName);
        //此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
        //登陆失败还到login页面
        return "system/login";
    }
}
